import {
  getTakeAwayUserBookPageList,
  commonUpdate,
  deleteTakeAwayUserBook
} from '@/services/takeAwayUserBookService';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Popconfirm, Space, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { dateFormat } from '@/utils/common';
import IconFontCN from '@/components/IconFontCN';
import { getCookie } from '@/utils/cookieUtils';

/**
 *
 * @constructor
 */
const TakeAwayUserBookPage: React.FC<unknown> = () => {
  const shopId = parseInt(getCookie("shopId") ?? "0");
  const [updateData, setUpdateData] = useState<TakeAwayUserBookType.TakeAwayUserBook>(
    {} as TakeAwayUserBookType.TakeAwayUserBook,
  );
  const actionRef = useRef<ActionType>();

  const showStatusName = (status: number) => {
    switch (status) {
      case 0:
        return "预定中";
      case 1:
        return "订单完成";
      default:
        return '';
    }
  }

  const finishBook = async (record: TakeAwayUserBookType.TakeAwayUserBook) => {
    await commonUpdate(record.Id, "Status", 1);
    message.success("操作成功！");
    actionRef.current?.reload();
  }

  /**
   *
   * @param
   */
  const doDelete = async (model: TakeAwayUserBookType.TakeAwayUserBook) => {
    const hide = message.loading('正在删除');
    if (!model?.Id) {
      return;
    }
    try {
      await deleteTakeAwayUserBook({
        id: model.Id,
      });
      message.success('操作成功');
      actionRef.current?.reload();
    } catch (e: any) {
      message.error('操作失败，' + e.message);
    } finally {
      hide();
    }
  };

  useEffect(() => {
    actionRef.current?.reload();
  }, [shopId])

  /**
   *
   */
  const columns: ProColumns<TakeAwayUserBookType.TakeAwayUserBook>[] = [
    {
      title: 'id',
      dataIndex: 'Id',
      hideInSearch: true,
    },
    {
      title: '餐桌区域',
      dataIndex: 'BoardTypeName',
      hideInSearch: true,
    },
    {
      title: '预定类型',
      dataIndex: 'BookTypeName',
      hideInSearch: true,
    },
    {
      title: '订单号',
      dataIndex: 'BookNumber',
    },
    {
      title: '预定人',
      dataIndex: 'OrderUserName',
    },
    {
      title: '性别',
      dataIndex: 'OrderUserSex',
      hideInSearch: true,
      renderText(text, record) {
        return record.OrderUserSex == 0 ? "男" : "女";
      },
    },
    {
      title: '预定人数',
      dataIndex: 'UserCount',
      hideInSearch: true,
    },

    {
      title: '订餐时间',
      dataIndex: 'OrderTime',
      hideInSearch: true,
      renderText(text, record) {
        return dateFormat(record.OrderTime, 'yyyy-mm-dd hh:mm:ss');
      },
    },
    {
      title: '备注',
      dataIndex: 'Description',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'Status',
      hideInSearch: true,
      render(dom, entity) {
        return showStatusName(entity.Status);
      },
    },
    {
      title: '创建时间',
      dataIndex: 'AddTime',
      hideInSearch: true,
      renderText(text, record) {
        return dateFormat(record.AddTime, 'yyyy-mm-dd hh:mm:ss');
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <Space split={<Divider type="vertical" />}>
          {record.Status == 0 ?
            <Popconfirm
              title="确定接受预定吗？"
              onConfirm={() => finishBook(record)}
              okText="确认"
              cancelText="取消"
            >
              <IconFontCN title='接单' onClick={() => { }} typeString='icon-daijiedan' />
            </Popconfirm>
            : null}
          <Popconfirm
            title="您确定要删除么？"
            onConfirm={() => doDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <ProTable<TakeAwayUserBookType.TakeAwayUserBook>
      headerTitle="订座管理"
      actionRef={actionRef}
      rowKey="id"
      search={{
        labelWidth: 'auto',
        defaultCollapsed: false,
      }}
      toolBarRender={() => []}
      request={async (params: any, sorter: any) => {
        const searchParams: PageInfo.PageRequest = {
          pageSize: params.pageSize,
          current: params.current
        };

        let sortQuery = "", filterQuery = `eq(ShopId,${shopId})`;
        // eslint-disable-next-line guard-for-in
        for (const key in sorter) {
          sortQuery += `${key}|${sorter[key]}`;
        }

        if (sortQuery != "") {
          searchParams['@sort'] = sortQuery;
        }

        for (const key in params) {
          if (key !== "pageSize" && key !== "current") {
            if (params[key] != "") {
              filterQuery += `contains(${key},${params[key]})&`;
              params[key] = '';
            }
          }
        }

        if (filterQuery != "") {
          searchParams['@filter'] = filterQuery;
        }

        searchParams['@relationships'] = "UserInfo,BoardType,BookType";
        const { Items, StatusCode } = await getTakeAwayUserBookPageList(searchParams);
        return {
          data: Items[0]?.Records || [],
          success: StatusCode === 200,
          total: Items[0].Total,
        } as any;
      }}
      columns={columns}
    />
  );
};

export default TakeAwayUserBookPage;
